<template>
  <div class="avatar" :style="{ width:imgWidth }">
    <span :style="{ backgroundColor: avatarColor, fontSize: size, width: imgWidth, height: imgWidth }">{{ user.userInfo.realName ? user.userInfo.realName.substring(0,1) : '' }}</span>
    <!-- <img v-if="true" :width="imgWidth" :src="user.userInfo.avatar" alt=""> -->
  </div>
</template>

<script>
import { EventBus } from '@/utils/event-bus'
import { mapState } from 'vuex'
export default {
  props: {
    imgWidth: {
      type: String,
      default: '40px'
    },
    size: {
      type: String,
      default: '20px'
    }
  },
  data() {
    return {
      avatarColor: '#ccc',
      colorList: [
        'rgb(120, 8, 120)',
        'rgb(255, 200, 0)',
        'rgb(64, 64, 64)',
        'rgb(34, 107, 171)',
        'rgb(26, 145, 114)',
        'rgb(162, 38, 34)'
      ]
    }
  },
  computed: {
    ...mapState([
      'user'
    ])
  },
  created() {
    EventBus.$on('updateAvatar', () => {
      this.getAvatarColor()
    })
    this.getAvatarColor()
  },
  methods: {
    getAvatarColor() {
      this.avatarColor = this.tranColor(this.user.userInfo.realName)
    },

    tranColor(name) {
      var index = name ? name[0].charCodeAt(0) % 6 : 1
      return this.colorList[index]
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.avatar{
  span {
    font-size: 20px;
    border-radius: 50%;
    display: flex;
    color: white;
    font-weight: bold;
    justify-content: center;
    align-items: center;
  }
  img{
    border-radius: 100%;
    vertical-align: middle;
  }
}
</style>
